document.getElementById('uploadForm').addEventListener('submit', async function (e) {
    e.preventDefault(); // 阻止表单默认提交

    const fileInput = document.getElementById("image-upload-learn2");
    const responseDiv = document.getElementById("response");
    // const fileInput = document.getElementById('fileInput');
    // const responseDiv = document.getElementById('response');

    if (fileInput.files.length === 0) {
        responseDiv.innerHTML = '<p class="text-danger">请先选择文件！</p>';
        return;
    }

    const file = fileInput.files[0];
    const formData = new FormData();
    formData.append('file', file);

    responseDiv.innerHTML = '<p class="text-info">上传中，请稍候...</p>';

    try {
        const uploadResponse = await fetch('/upload_questionImage', { method: 'POST', body: formData });
        const result = await uploadResponse.json();

        if (result.error) {
            responseDiv.innerHTML = `<p class="text-danger">上传失败：${result.error}</p>`;
            return;
        }

        const extractedText = result.ocrResult;
        console.log("提取的文本：", extractedText);

        if (!extractedText || extractedText.trim() === "") {
            responseDiv.innerHTML = `<p class="text-danger">提取的文本为空，无法进行搜题。</p>`;
            return;
        }

        responseDiv.innerHTML = `
            <p class="text-success">上传成功！</p>
<!--            <p><strong>提取的内容：</strong> ${extractedText}</p>-->
            <p><strong>开始搜题...</strong></p>
        `;

        const searchResponse = await fetch('/search_question', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ question: extractedText })
        });

        const searchResult = await searchResponse.json();

        if (searchResult.error) {
            responseDiv.innerHTML += `<p class="text-danger">搜题失败：${searchResult.error}</p>`;
        } else {
            // responseDiv.innerHTML += `<p><strong>搜题结果：</strong> ${searchResult.answer}</p>`;
            // 显示搜题结果
            let resultHtml = `<p><strong>搜题结果：</strong></p>`;
            if (Array.isArray(searchResult.answer) && searchResult.answer.length > 0) {
                // 处理多个结果
                searchResult.answer.forEach((item, index) => {
                    resultHtml += `
                                        <p><strong>问题 ${index + 1}：</strong> ${item.question}</p>
                                        <p><strong>答案：</strong> ${item.answer}</p>
                                    `;
                });
            } else {
                // 单个结果
                resultHtml += `<p><strong>答案：</strong> ${searchResult.answer}</p>`;
            }
            responseDiv.innerHTML += resultHtml;
        }
    } catch (error) {
        console.error("上传或搜题错误：", error);
        responseDiv.innerHTML = `<p class="text-danger">发生错误：${error.message}</p>`;
    }
});